package com.fs.service;

import com.fs.dao.MonitorCatFailSqlDao;
import com.fs.domain.MonitorCatFailSql;
import com.fs.util.DateUtil;
import com.fs.vo.MonitorCatFailSqlVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by fengshuai on 17/5/19.
 */
@Service
public class MonitorCatFailSqlService {

    @Autowired
    private MonitorCatFailSqlDao monitorCatFailSqlDao;

    public List<MonitorCatFailSqlVo> batchGetByDay(int day) {
        List<MonitorCatFailSql> domains = this.monitorCatFailSqlDao.batchGetByDay(day);
        Map<String, MonitorCatFailSql> utilMap = new HashMap<>();
        for (MonitorCatFailSql domain : domains) {
            utilMap.put(domain.getFail_sql() + "-" + domain.getHour(), domain);
        }
        Map<String, MonitorCatFailSqlVo> voMap = new HashMap<>();
        for (String key : utilMap.keySet()) {
            MonitorCatFailSqlVo vo = voMap.get(utilMap.get(key).getFail_sql());
            if (vo == null) {
                vo = new MonitorCatFailSqlVo();
                vo.setDay(DateUtil.dateString2String(String.valueOf(day), "YYYYMMdd"));
                vo.setFailSql(utilMap.get(key).getFail_sql());
                voMap.put(utilMap.get(key).getFail_sql(), vo);
            }
            if (StringUtils.isBlank(vo.getHours())) {
                vo.setHours(String.valueOf(utilMap.get(key).getHour()));
            } else {
                vo.setHours(vo.getHours() + "," + String.valueOf(utilMap.get(key).getHour()));
            }
            vo.setTimes(vo.getTimes() + utilMap.get(key).getTimes());
        }
        List<MonitorCatFailSqlVo> vos = new ArrayList<>(voMap.values());
        Collections.sort(vos, new Comparator<MonitorCatFailSqlVo>() {
            @Override
            public int compare(MonitorCatFailSqlVo o1, MonitorCatFailSqlVo o2) {
                return Integer.compare(o2.getTimes(), o1.getTimes());
            }
        });
        for (MonitorCatFailSqlVo vo : vos) {
            String[] hours = vo.getHours().split(",");
            Arrays.sort(hours, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
                }
            });
            vo.setHours(Arrays.asList(hours).toString());
        }
        return vos;
    }
}
